package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	fmt.Println("客户端开始链接啦")
	conn, err := net.Dial("tcp", "192.168.3.122:8898")
	if err != nil {
		fmt.Printf("client error: %v\n", err)
		return
	}
	defer conn.Close()
	fmt.Printf("客户端链接成功: local addr: %v\n", conn.LocalAddr().String())
	fmt.Printf("客户端链接成功: remote addr: %v\n", conn.RemoteAddr().String())
	//	功能1
	//sendOneLineData(conn)
	// 功能2
	sendMultipleLineData(conn)
}

func sendOneLineData(conn net.Conn) {
	fmt.Println("写点东西给服务端吧:")
	reader := bufio.NewReader(os.Stdin)
	line, err := reader.ReadString('\n')
	if err != nil {
		fmt.Printf("readString error: %v\n", err)
		return
	}
	n, err := conn.Write([]byte(line))
	if err != nil {
		fmt.Printf("conn Wtire error: %v\n", err)
		return
	}
	fmt.Printf("客户端发送了 %d 字节的数据", n)
}

func sendMultipleLineData(conn net.Conn) {
	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Println("写点东西给服务端吧:")
		line, err := reader.ReadString('\n')
		if err != nil {
			fmt.Printf("readString error: %v\n", err)
			continue
		}
		if strings.Trim(line, "\r\n") == "exit" {
			fmt.Println("结束客户端")
			return
		}
		n, err := conn.Write([]byte(line))
		if err != nil {
			fmt.Printf("conn Wtire error: %v\n", err)
			continue
		}
		fmt.Printf("客户端发送了 %d 字节的数据\n", n)
	}

}
